package com.qin.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexProcessor {

    /*
     * 1、根据正则表达式regex，匹配inputString
     * 2、返回匹配结果
     */
    public List<String> getStringByRegex(String inputString, String regex){

        List outputList = new ArrayList();

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputString);

        while(matcher.find()){
            outputList.add(matcher.group(1));
        }

        return outputList;
    }

    /*
     * 1、根据正则表达式regex数组，匹配inputString
     * 2、返回第一个匹配的结果
     */
    public String getStringByRegexes(String inputString, String[] regexes){

        String outputString = null;

        for(int i=0; i<regexes.length; i++){

            Pattern pattern = Pattern.compile(regexes[i]);
            Matcher matcher = pattern.matcher(inputString);

            while(matcher.find()){
                outputString = matcher.group(1);
                return outputString;
            }
        }

        return outputString;
    }

    /*
     * 1、根据正则表达式regex数组，匹配inputString
     * 2、返回第一个匹配的结果
     */
    public String replaceStringByMap(String inputString, Map<String, String> map){

        String outputString = inputString;

        //从inputString匹配字符串#{xx}
        List<String> replaceList = getStringByRegex(inputString, "(#\\{.+?\\})");

        for(int i=0; i<replaceList.size(); i++){

            //获取待替换字符串 #{xxx}
            String replaceString = replaceList.get(i);
            //获取待替换变量名 xxx
            String targetPara = replaceString.substring(2, replaceList.get(i).length()-1);

            //把inputString中的 #{xxx}，替换成 map.get(xxx)
            if(map.get(targetPara) != null){
                outputString = outputString.replace(replaceString, map.get(targetPara));
            }
        }

        return outputString;
    }
}
